import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { Router, Event as RouterEvent, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
import { LoaderComponent } from './shared/components/loader/loader.component';
import { SpinnerComponent } from './shared/components/spinner/spinner.component';
import { ToastsManager } from 'ng2-toastr';
import { AppService } from './app.service';
import { StorageService } from './shared/services/storage.service';
import { AnalyticsService } from './shared/services/googleAnalytics.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  public loggedIn: boolean = false;

  @ViewChild('loader') private loader: LoaderComponent;
  @ViewChild('spinner') private spinner: SpinnerComponent;

  constructor(
    private router: Router, 
    private toastr: ToastsManager, 
    private vcr: ViewContainerRef,
    private analyticsService: AnalyticsService) {
    this.toastr.setRootViewContainerRef(vcr);
    setTimeout(() => {
      AppService.set(this.loader, this.spinner);
    });
    router.events.subscribe((event: RouterEvent) => {
      this.navigationInterceptor(event);
    });
    
    //on page refresh, reset the google analytics config
    if(StorageService.get().userInfo)
      this.analyticsService.config();
  }

  ngDoCheck() {
    this.loggedIn = StorageService.get() && StorageService.get().authData !== null;;
  }

  onActivate(event) {
    window.scroll(0, 0);
  }

  ngOnDestroy(){
    this.analyticsService.close();
  }

  // Shows and hides the loading spinner during RouterEvent changes
  navigationInterceptor(event: RouterEvent): void {
    if (event instanceof NavigationStart) {
      this.loader.start();
      this.spinner.show();
    }

    if (event instanceof NavigationEnd) {

    }

    // Set loading state to false in both of the below events to hide the spinner in case a request fails
    if (event instanceof NavigationCancel) {
      this.finishLoading();
    }
    if (event instanceof NavigationError) {
      this.finishLoading();
    }
  }

  public finishLoading() {
    this.loader.end();
    this.spinner.hide();
  }

  public startLoading(){
    this.loader.start();
    this.spinner.show();
  }
  
  public showError(errorMessage:string = 'This is not good!') {
    this.toastr.error(errorMessage, 'Error');
  }

  public showSuccess(message: string, title?: string){
    this.toastr.success(message, title);
  }

  public showWarning(message: string, title?: string){
    this.toastr.warning(message, title);
  }
}
